package com.module.overview.ui.schedule

import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppBackPressedFragment
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.overView.CardSettingListModel
import com.common.app.data.bean.overView.CardSettingModel
import com.common.app.helper.EventUmengAgent
import com.common.app.helper.RouterHelper
import com.common.app.helper.UmengAgentHelper
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.*
import com.common.base.utils.*
import com.common.base.utils.StatusBarUtils.setStatusBarHeight
import com.common.base.widget.CustomTextView
import com.common.base.widget.animator.CustomAnimation1
import com.facebook.drawee.view.SimpleDraweeView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.module.overview.databinding.OverviewFragmentMainBinding
import com.module.overview.ui.cardHistoryDetails.provider.OvSignsHrCardProvider
import com.module.overview.ui.historicalData.HistoricalDataMainActivity
import com.module.overview.ui.schedule.provider.OvMainActivityCardProvider
import com.module.overview.ui.schedule.provider.OvMainPressureCardProvider
import com.module.overview.ui.schedule.provider.OvMainSignsCardProvider
import com.module.overview.ui.schedule.provider.OvMainSleepCardProvider
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/10/12
 * <p>
 * 描述：概览模块首页
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_OVERVIEW_FRAGMENT)
class OverviewFragment : AppBackPressedFragment<OverviewFragmentMainBinding, OverviewViewModel>(), View.OnClickListener{

    override fun getViewModel(): Class<OverviewViewModel> = OverviewViewModel::class.java

    override fun getViewBinding() = OverviewFragmentMainBinding.inflate(layoutInflater)

    private val cardAdapter by lazy { OverviewMainCardAdapter() }

    private val classicsFooter by lazy { ClassicsFooter(requireActivity()) }

    private lateinit var headView: View
    private lateinit var footerView: View

    var mData = mutableListOf<CardSettingModel>()

    override fun initViews() {
        super.initViews()
        setStatusBarHeight(mViewBinding.statusView)

//        headView = layoutInflater.inflate(R.layout.overview_main_head_crad_view, null)
        headView = layoutInflater.inflate(R.layout.base_rlv_margin_footer_tr_view25, null)
        footerView = layoutInflater.inflate(R.layout.overview_main_foot_crad_view, null)

        cardAdapter.apply {
            cardAdapter.addHeaderView(headView)
            cardAdapter.addFooterView(footerView)
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = true
            mViewBinding.hrv.adapter = this
        }
//        headView.findViewById<SimpleDraweeView>(R.id.imgSummaryReportBg).setOnClickListener(onClick = object : View.OnClickListener {
//            override fun onClick(p0: View?) {
//                RouterHelper.navigation(RouterHub.ROUTER_OVERVIEW_SUMMARY_REPORT_MAIN)
//            }
//        })
//        headView.findViewById<SimpleDraweeView>(R.id.imgHistoricalDataBg).setOnClickListener(onClick = object : View.OnClickListener {
//            override fun onClick(p0: View?) {
//                requireActivity().startActivity<HistoricalDataMainActivity>(false)
//            }
//        })
//        headView.findViewById<SimpleDraweeView>(R.id.tvHistoricalData).setOnClickListener(onClick = object : View.OnClickListener {
//            override fun onClick(p0: View?) {
//            }
//        })
    }

    override fun lazyInitData() {
        super.lazyInitData()

        try {
            SpUtilsManagement.getParcelable(KeyPre.KEY_OV_CARD_CONFIG, CardSettingListModel::class.java)?.let {
                setCardConfigUI(it.mData as MutableList<CardSettingModel>?)
            }
        } catch (e: OutOfMemoryError) {
            // 清理损坏的数据
            SpUtilsManagement.removeFromKey(KeyPre.KEY_OV_CARD_CONFIG)
            // 重新初始化默认配置
            initDefaultCardConfig()
        } catch (e: Exception) {
            // 处理其他反序列化异常
            SpUtilsManagement.removeFromKey(KeyPre.KEY_OV_CARD_CONFIG)
            initDefaultCardConfig()
        }
        cardAdapter.setList(mData)

        getAllScoringFactors()
    }

    override fun initEvents() {
        super.initEvents()

        //上下拉刷新
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }
        mViewBinding.pdView.setRefreshHeader(
            ClassicsHeader(requireActivity())
                .setAccentColor(
                    ContextCompat.getColor(requireActivity(), R.color.white)
                )
        )
        classicsFooter.setAccentColor(
            ContextCompat.getColor(
                requireActivity(),
                R.color.color_999999
            )
        )
        mViewBinding.pdView.setRefreshFooter(classicsFooter)

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewBinding.pdView.finishLoadMore()
                mViewBinding.pdView.finishLoadMoreWithNoMoreData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                cardAdapter.notifyDataSetChanged()
                getAllScoringFactors()
//                HeartRateRepo.instance.deleteAll()//测试
                refreshLayout.layout.postDelayed({
                    finishPdView()
                }, 1000)
            }
        })

        LiveEventBus.get(KeyEvents.KEY_OV_REFRESH_CONFIG, CardSettingListModel::class.java).observe(this) {cardSettingListModelIt->
            cardSettingListModelIt.mData?.let { mDataIt->
                setCardConfigUI(mDataIt as MutableList<CardSettingModel>?)
            }
        }

        footerView.findViewById<ConstraintLayout>(R.id.totalEditCardCard).setOnClickListener(onClick = object : View.OnClickListener {
            override fun onClick(p0: View?) {
                RouterHelper.navigation(RouterHub.ROUTER_OVERVIEW_EDIT_CARD)
            }
        })

    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        StatusBarUtils.setStatusBarForegroundColor(activity, true)
        UmengAgentHelper.onEvent(EventUmengAgent.visit_overview_main)
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onClick(v: View?) {
        when (v) { // 处理点击事件
        }
    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
        mViewBinding.pdView.setNoMoreData(true)
    }

    private fun initDefaultCardConfig() {
        val mData = mutableListOf<CardSettingModel>()
        mData.add(CardSettingModel(name = AppUtils.getString(R.string.common_sleep_hint), sortOrder = 1, itemType = AllCardTypeConfig.TYPE_CARD_SLEEP))
        mData.add(CardSettingModel(name = AppUtils.getString(R.string.common_activity_hint), sortOrder = 2, itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY))
        mData.add(CardSettingModel(name = AppUtils.getString(R.string.common_pressure_hint), sortOrder = 3, itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE))
        mData.add(CardSettingModel(name = AppUtils.getString(R.string.common_signs_hint), sortOrder = 4, itemType = AllCardTypeConfig.TYPE_CARD_SIGNS))
        mData.add(CardSettingModel(name = AppUtils.getString(R.string.common_exercise_hint), sortOrder = 5, itemType = AllCardTypeConfig.TYPE_CARD_EXERCISE))

        val cardSettingListModel = CardSettingListModel(mData)
        SpUtilsManagement.putParcelable(KeyPre.KEY_OV_CARD_CONFIG, cardSettingListModel)
        setCardConfigUI(mData)
    }

    fun setCardConfigUI(mDataIt: MutableList<CardSettingModel>?){
        // 1. 首先检查 mDataIt 是否为 null 或空
        if (mDataIt.isNullOrEmpty()) {
            // 如果为空，可以选择使用默认配置或者直接返回
            return
        }

        // 2. 过滤掉 null 元素
        val validData = mDataIt.filterNotNull()
        if (validData.isEmpty()) {
            // 如果过滤后没有有效数据，直接返回
            return
        }

        // 3. 保存有效数据
        SpUtilsManagement.putParcelable(KeyPre.KEY_OV_CARD_CONFIG, CardSettingListModel(validData))

        // 创建一个新的列表来存储更新后的数据
        val updatedData = mutableListOf<CardSettingModel>()

        // 遍历有效数据
        validData.forEach { receivedCard ->
            // 确保 receivedCard 不为 null（虽然已经过滤过了，但为了安全起见）
            receivedCard?.let { card ->
                if (card.isEnabled) {
                    // 如果卡片启用，查找mData中是否已存在该类型的卡片
                    val existingCard = mData.find { it.itemType == card.itemType }
                    if (existingCard != null) {
                        // 如果存在，更新排序并添加到新列表
                        existingCard.sortOrder = card.sortOrder
                        existingCard.isEnabled = true
                        updatedData.add(existingCard)
                    } else {
                        // 如果不存在，创建新卡片并添加到新列表
                        updatedData.add(CardSettingModel(
                            id = "",
                            name = card.name,
                            isEnabled = true,
                            sortOrder = card.sortOrder,
                            itemType = card.itemType
                        ))
                    }
                }
            }
        }

        // 根据排序顺序排序
        updatedData.sortBy { it.sortOrder }

        // 更新mData并刷新适配器
        mData.clear()
        mData.addAll(updatedData)
        cardAdapter.setList(mData)
    }

    private fun getAllScoringFactors() {
        showDialogLoading()

        mViewModel.getAllScoringFactors(TimeUtils.getYearMonthDay(TimeUtils.getTimeDateLong())) {
            dismissLoadingDialog()
            finishPdView()
            showToast(it.getShowMsg())
        }.observe(this) {
            finishPdView()
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    it.Data?.let { dataIt ->
                        dataIt.list?.forEach {listIt->

                            when(listIt.analysis_type){
                                "activity"->{
                                }
                                "stress"->{
                                }
                                "vital_sign"->{
                                    (cardAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS) as OvMainSignsCardProvider).let { providerIt->
                                        providerIt.tvOverallScoring?.text = listIt.total_score.toString()
                                        providerIt.rpdSigns?.setProgressWithAnimation(listIt.total_score)
                                    }
                                }
                                "sleep"->{
                                    (cardAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SLEEP) as OvMainSleepCardProvider).let { providerIt->
                                        providerIt.tvOverallScoring?.text = listIt.total_score.toString()
                                        providerIt.rpdSleep?.setProgressWithAnimation(listIt.total_score)
                                    }
                                }
                                else->{

                                }
                            }
                        }
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }
}